<template>
  <div class="sample-list">
    <el-table :data="samples" style="width: 100%">
      <el-table-column prop="name" label="样本名称"></el-table-column>
      <el-table-column prop="code" label="样本编号"></el-table-column>
      <el-table-column prop="fileName" label="文件名称"></el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleUpload(scope.row)">上传文件</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 文件上传对话框 -->
    <el-dialog title="文件上传" :visible.sync="uploadDialogVisible" width="500px">
      <div class="upload-container">
        <el-upload class="upload-demo" drag action="#" :auto-upload="false" :on-change="handleFileChange"
          :show-file-list="false">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>

        <div v-if="currentFile" class="file-info">
          <p>文件名：{{ currentFile.name }}</p>
          <p>文件大小：{{ formatFileSize(currentFile.size) }}</p>
          <el-progress :percentage="uploadProgress"></el-progress>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="startUpload" :loading="uploading" :disabled="!currentFile">开始上传</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import SparkMD5 from 'spark-md5'

export default {
  name: 'SampleList',
  data() {
    return {
      samples: [],
      uploadDialogVisible: false,
      currentFile: null,
      currentSample: null,
      uploadProgress: 0,
      uploading: false,
      uploadStatus: '',
      chunkSize: 1024 * 1024, // 1MB
      fileHash: '',
      uploadedChunks: []
    }
  },
  computed: {
    progressStatus() {
      // 根据uploadStatus返回Element UI Progress组件支持的状态
      switch (this.uploadStatus) {
        case 'success':
          return 'success'
        case 'exception':
          return 'exception'
        default:
          return ''
      }
    }
  },
  created() {
    this.fetchSamples()
  },
  methods: {
    async fetchSamples() {
      try {
        const response = await this.$http.get('/samples')
        this.samples = response.data.content
      } catch (error) {
        console.log(error);

        this.$message.error('获取样本列表失败')
      }
    },
    handleUpload(sample) {
      this.currentSample = sample
      this.uploadDialogVisible = true
      this.resetUploadState()
    },
    resetUploadState() {
      this.currentFile = null
      this.uploadProgress = 0
      this.uploading = false
      this.uploadStatus = ''
      this.fileHash = ''
      this.uploadedChunks = []
    },
    async handleFileChange(file) {
      this.currentFile = file.raw
      this.uploadProgress = 0
      this.uploadStatus = ''
      // 计算文件哈希值
      this.fileHash = await this.calculateFileHash(this.currentFile)
    },
    async calculateFileHash(file) {
      return new Promise((resolve) => {
        const reader = new FileReader()
        reader.readAsArrayBuffer(file)
        reader.onload = (e) => {
          const buffer = e.target.result
          const spark = new SparkMD5.ArrayBuffer()
          spark.append(buffer)
          const hash = spark.end()
          resolve(hash)
        }
      })
    },
    formatFileSize(size) {
      if (size < 1024) {
        return size + 'B'
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(2) + 'KB'
      } else {
        return (size / (1024 * 1024)).toFixed(2) + 'MB'
      }
    },
    async startUpload() {
      if (!this.currentFile) return

      this.uploading = true
      try {
        // 初始化上传
        const initResponse = await this.$http.post('/files/init', null, {
          params: {
            fileName: this.currentFile.name,
            fileHash: this.fileHash,
            totalSize: this.currentFile.size
          }
        })

        const fileInfo = initResponse.data
        if (fileInfo.uploadedSize > 0) {
          // 如果存在未完成的上传，继续上传
          this.uploadedChunks = Math.ceil(fileInfo.uploadedSize / this.chunkSize)
          this.uploadProgress = (fileInfo.uploadedSize / this.currentFile.size) * 100
        }

        // 开始分片上传
        const chunks = Math.ceil(this.currentFile.size / this.chunkSize)
        for (let i = this.uploadedChunks; i < chunks; i++) {
          const start = i * this.chunkSize
          const end = Math.min(start + this.chunkSize, this.currentFile.size)
          const chunk = this.currentFile.slice(start, end)

          const formData = new FormData()
          formData.append('chunk', chunk)
          formData.append('fileHash', this.fileHash)
          formData.append('chunkNumber', i + 1)

          await this.$http.post('/files/chunk', formData)

          this.uploadedChunks++
          this.uploadProgress = (this.uploadedChunks / chunks) * 100
        }

        // 完成上传
        await this.$http.post(`/files/complete/${this.fileHash}`)

        // 更新样本信息
        await this.$http.put(`/samples/${this.currentSample.id}`, {
          ...this.currentSample,
          fileName: this.currentFile.name
        })

        this.uploadStatus = 'success'
        this.$message.success('上传成功')
        this.fetchSamples()
        this.uploadDialogVisible = false
      } catch (error) {
        this.uploadStatus = 'exception'
        this.$message.error('上传失败：' + error.message)
      } finally {
        this.uploading = false
      }
    }
  }
}
</script>

<style scoped>
.upload-container {
  padding: 20px;
}

.file-info {
  margin-top: 20px;
}

.file-info p {
  margin: 5px 0;
}
</style>